package ext.tianma.part.util.emailService;

import java.io.Closeable;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;

import ext.tianma.bom.util.ClassificationUtil;
import ext.tianma.bom.util.StringUtil;
import ext.tianma.doc.util.GetResearchSite;
import ext.tianma.part.forms.TMTypeUtil;
import ext.tianma.util.IbaAttributeUtil;
import ext.com.iba.IBAUtil;
import ext.tianma.MaterialClassification.CreatePartClassificationUtil;
import ext.tianma.bom.service.MaterialsApplicationService;
import ext.tianma.bom.service.SelectPartService;
import wt.csm.navigation.ClassificationNode;
import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.iba.value.ReferenceValue;
import wt.mail.EMailMessage;
import wt.method.RemoteAccess;
import wt.part.WTPart;
import wt.pom.PersistenceException;
import wt.query.QueryException;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.util.WTException;

/**
 * 新材料建立及材料变更，在PLM系统中增加传递到SQE功能
 * 
 * @author laichao_sun
 *
 */

public class PartUpgradeEmailToSQE implements RemoteAccess, Serializable {
	private static final long serialVersionUID = 8688935611735680694L;
	public static String path = "/ptc/Windchill/codebase/ext/tianma/part/config/PartUpgradeEmailToSQE.xls";

	public static void PartUpgradeEmailToSQE(Object object,String string) {
		System.out.println("SLC ==开始邮件提醒SQE==>");
		Workbook we = null;
		InputStream in = null;

		try {
			WTPart part = null;
			if (object instanceof WTPart) {
				part = (WTPart) object;

				in = new FileInputStream(path);
				we = WorkbookFactory.create(in);
				if (null == path || path.equals("")) {
					throw new WTException("没有获取到新材料建立及材料变更的配置路径，请检查!");
				}
				if (null == in || null == we) {
					throw new WTException("没有获取到新材料建立及材料变更的配置路径，请检查!");
				}

				// 获取分类全路径
				String classification = ClassificationUtil.getClassification(part);
				System.out.println("分类属性:" + classification);
				String email = "";

				// 通过配置文件获取发送邮件的人员的邮箱
				email = getCode(we.getSheetAt(0), classification);
				if (StringUtil.isNullOrEmpty(email)) {

				} else {
					// 发送邮件
					String content = content(part,string);
					String titleStr = "料号升级通知提醒";
					//System.out.println("SLC ==email==>"+email);
					boolean flag = sendEmail(email, content, titleStr);
					System.out.println("SLC ==结束邮件提醒SQE==>" + flag);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(in);
		}

	}

	// 拼接邮件内容
	private static String content(WTPart part,String string) throws PersistenceException, WTException, RemoteException {
		String content = "";
		String infoPage = "";
		String number = "";
		String url = "";

		number = part.getNumber();

		// 生效地
		//Vector effectiveSite = (Vector) IBAUtil.getIBAValue2(part, "partNumberEffectiveSite");
		//System.out.println("生效地c:" + effectiveSite);
		List<String> list = IbaAttributeUtil.getAttributeValues(part, "partNumberEffectiveSite");
		List<String> list2 = new  ArrayList<String>();
		for(String s :list ) {
			String d = GetResearchSite.getEnumerationDisplayValue("料号生效产地",s);
			list2.add(d);
		}
		//System.out.println("生效地显示名称:"+list2);
		
		
		// 申请原因
		String reason = IbaAttributeUtil.getAttributeValue(part, "partApplicationReason");
		//System.out.println("申请原因:" + reason);

		url = SelectPartService.generateInfoPageURL(part);
		infoPage = "<a target='_blank' href='" + url + "'>" + number + "</a>";

		content = "原材料料号为:" + infoPage +",进行了"+string+ ",生效地为:" + list2 + ",申请原因:" + reason + ",请处理!";

		return content;
	}

	// 通过判断分类属性来获取邮箱
	private static String getCode(Sheet sheet, String classification) {
		try {
			for (int i = 1; i < sheet.getLastRowNum() + 1; i++) {
				Row row = sheet.getRow(i);
				String temp = getCellValue(row.getCell(0)).trim();
				if (null == temp || temp.equals("")) {
					continue;
				} else {
					if (classification.contains(temp)) {
						String temp2 = getCellValue(row.getCell(1)).trim();
						return temp2;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 发送邮件
	 * 
	 * @param userName
	 * @param content
	 * @param titleStr
	 * @return
	 */
	public static boolean sendEmail(String emailAddr, String content, String titleStr) {
		try {
			System.out.println("emailAddr======" + emailAddr);
			// 邮件内容
			StringBuffer body = new StringBuffer();
			body.append(content);
			String[] emailSendTo = "".equals(emailAddr) || emailAddr == null ? null : emailAddr.split(";");// 2、why？
			EMailMessage email = EMailMessage.newEMailMessage();
			email.addEmailAddress(emailSendTo);
			// 邮件主题
			StringBuffer title = new StringBuffer();
			title.append(titleStr);
			email.setSubject(title.toString());
			email.setMultipartSubtype("text/html;charset=\"UTF8\"");
			email.addPart(body.toString(), "text/html;charset=\"UTF8\"");
			email.send(false);
			return true;
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}

	}

	/**
	 * 获取单元格中的信息
	 * 
	 * @param cell 单元格
	 * @return 主要参数信息
	 * @throws Exception
	 */
	public static String getCellValue(Cell cell) throws WTException {
		String value = "";
		try {
			if (null == cell) {
				return "";
			}
			switch (cell.getCellType()) {
			case XSSFCell.CELL_TYPE_NUMERIC:
				value = Double.toString(cell.getNumericCellValue());
				break;
			case XSSFCell.CELL_TYPE_STRING:
				value = cell.getStringCellValue();
				break;
			case XSSFCell.CELL_TYPE_BLANK:
				value = "";
				break;
			case XSSFCell.CELL_TYPE_BOOLEAN:
				value = Boolean.toString(cell.getBooleanCellValue());
				break;
			case XSSFCell.CELL_TYPE_FORMULA:
				try {
					value = String.valueOf(cell.getNumericCellValue());
				} catch (Exception e) {
					value = cell.getStringCellValue();
				}
				break;
			default:
				break;
			}
		} catch (Exception e) {
		}

		return value.trim();
	}

	/**
	 * 关闭资源
	 * 
	 * @param closeable
	 */
	public static void close(Closeable closeable) {
		try {
			if (closeable != null) {
				closeable.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
